package cn.yy.cloudpay.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newland.mtype.ModuleType;
import com.newland.mtype.module.common.light.IndicatorLight;
import com.newland.mtype.module.common.light.LightType;
import com.newland.mtype.module.common.printer.PrintContext;
import com.newland.mtype.module.common.printer.Printer;
import com.newland.mtype.module.common.printer.PrinterResult;
import com.ys.serviceapi.api.YSSDKManager;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.yy.cloudpay.MainActivity;
import cn.yy.cloudpay.R;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.cardread.FeixiScanT2Activity;
import cn.yy.cloudpay.db.RecordDB;
import cn.yy.cloudpay.db.RecordModel;
import cn.yy.cloudpay.listener.ITitlebarClickListener;
import cn.yy.cloudpay.scan.FeixiScanTActivity;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.KeyboardStringUtil;
import cn.yy.cloudpay.util.ObjectGenerator;
import cn.yy.cloudpay.util.PrinterStringUtil;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.util.WebserviceRequset;
import cn.yy.cloudpay.view.LoadingDialog;
import cn.yy.cloudpay.view.MyGridAdapter;
import cn.yy.cloudpay.view.MyGridView;
import cn.yy.cloudpay.view.TitlebarLayout;
import cn.yy.cloudpay.view.ToastUtil;
import cn.yy.pos.launcher.service.IOperatorService;
import cn.yy.pos.launcher.service.Operator;
import cn.yy.pos.launcher.service.Payway;

public class PayActivity extends BaseActivity {
	public Logger log= Logger.getLogger(this.getClass());

	public MyGridView gridview;
	public Context mContext;
	public IOperatorService mService;
	public CloudPayApplication mApplication;
	public TitlebarLayout titlebar;
	public RelativeLayout relativeLayout;
	public LoadingDialog mProgress;
	public int mPayType;
	public String mSummary; // 以分为单位的金额
	public String mAmount;
	public int mOpType;
	public Printer printer;
	public String businessRstStr;
	public String bankPayType = "";
	public boolean mIsServiceConn = false;
	public boolean isFromWelfare = false;//是否从人人公益支付
	public String isFromType = "";//1,移动开单
	public IndicatorLight light;
	public String totalMoney;
	public String orderNum;
	public String scanMoney;
	public String transType;
	public String type;
	public String payType;
	public String scanCode;
	public String orderId;
	public Map<String,String> orderMap = new HashMap<String,String>();
	public int orderix=0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		mApplication = (CloudPayApplication) getApplication();
		showVerson();
		initView();
		getOperatorFrmoRemote();
		if("1".equals(mApplication.isMT())){
			try {
				light = (IndicatorLight) mApplication.getDeviceInstance().getStandardModule(ModuleType.COMMON_INDICATOR_LIGHT);
				light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
			} catch (Exception e) {
				ToastUtil.showToast(mContext, "指示灯初始化异常" + e.toString(), ToastUtil.WARNING);
				e.printStackTrace();
			}
		}
		initParam();
	}


	public void initParam(){
		isFromWelfare = getIntent().getBooleanExtra("from_welfare", false);
		isFromType = getIntent().getStringExtra("from_type");
		totalMoney =  getIntent().getStringExtra("totalMoney");
		orderNum =  getIntent().getStringExtra("orderNum");
		transType = getIntent().getStringExtra("transType");
		type = getIntent().getStringExtra("type");
	}


	private void getOperatorFrmoRemote() {
		Intent intent = new Intent("cn.yy.pos.launcher.service.RemoteService");
		bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
	}

	private void initView() {
		gridview=(MyGridView) findViewById(R.id.gridview);
		mProgress = new LoadingDialog(mContext, "正在支付，请稍后");
		relativeLayout = (RelativeLayout) findViewById(R.id.include1);
		titlebar = new TitlebarLayout(mContext, relativeLayout, "收款");
		titlebar.setTitlebarClickListener(new ITitlebarClickListener() {
			@Override
			public void OnRetrunListener(View view) {
				onBackPressed();
			}
		});
	}


	private void initOperatorInfo(){
		try {
			if(mService != null){
				mApplication.setOperator(mService.getOperator());
				mApplication.setServiceAddress(mService.getServerAddress());

				if(mApplication.getOperator() == null){
					mApplication.setOperator(new Operator());
				}
//				Toast.makeText(mContext, "刷卡通道："+mApplication.getOperator().getBankType(), Toast.LENGTH_LONG).show();
				if(!StringUtil.isEmpty(mApplication.getOperator().getBankType())){
					bankPayType = mApplication.getOperator().getBankType();
				}else{
					bankPayType = Constant.BANKPAYTYPE_YINGSHEN;
				}
				iniGridView();
			}else{
				ToastUtil.showToast(mContext, "获取操作员信息异常：mService为null", ToastUtil.WARNING);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ToastUtil.showToast(mContext, "获取操作员信息异常"+e.toString(), ToastUtil.WARNING);
		}
	}



	private void iniGridView(){
		if(mApplication.getOperator()==null){
			ToastUtil.showToast(mContext, "请登录系统", ToastUtil.WARNING);
			return;
		}
		ArrayList<Payway> payways = mApplication.getOperator().getPayways();
		if(payways==null){
			payways = new ArrayList<Payway>();
		}
		Collections.sort(payways, new Comparator<Payway>(){
			public int compare(Payway o1, Payway o2) {
				if(Integer.valueOf(o1.getFlag()) > Integer.valueOf(o2.getFlag())){
					return 1;
				}
				if(Integer.valueOf(o1.getFlag()) == Integer.valueOf(o2.getFlag())){
					return 0;
				}
				return -1;
			}
		});
		String[] box_text = new String[payways.size()];
		int[] box_imgs = new int[payways.size()];
		for(int i=0;i<payways.size();i++){
			Payway payway = payways.get(i);
			box_text[i] = payway.getPaywayname();
			String png = "pp_"+ payway.getPaywaynum();
			box_imgs[i] = this.getResource(png);
		}
		gridview.setAdapter(new MyGridAdapter(this, box_text, box_imgs));

		unbindService(mServiceConnection);
		intoFeixi(payways);

	}

	public void intoFeixi(ArrayList<Payway> payways){
		for(Payway payway:payways){
			if(payway.getPaywaynum().equals(Constant.PAY_WAY_FEIXIPAY)){
				Intent intent = new Intent();
				intent.putExtra(Constant.PARAM_OPTYPE, mOpType);
				intent.putExtra(Constant.PARAM_AMOUNT, mAmount);
				intent.putExtra(Constant.PARAM_SUMMARY, mSummary);
				intent.putExtra(Constant.PARAM_PAYTYPE, mPayType);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);  // 无动画
				intent.setClass(PayActivity.this, FeixiScanT2Activity.class);
				startActivityForResult(intent, Constant.GREQUEST_CODE_SCANNIN);
				overridePendingTransition(R.anim.empty,R.anim.empty);
			}
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			businessRstStr = (String) msg.obj; // 扫描到的授权码或支付后返回的消息
			switch (msg.what) {
				case Constant.BUSINESS_SERVICE_CONNED: // 与主界面service连接成功
					initOperatorInfo();
					showVerson();
					break;
				default:
					break;
			}
		}
	};

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			try {
				mService = IOperatorService.Stub.asInterface(service);
				mApplication.setOperator(mService.getOperator());
				mApplication.setServiceAddress(mService.getServerAddress());

				Message message = new Message();
				message.what = Constant.BUSINESS_SERVICE_CONNED;
				mHandler.sendMessage(message);
			} catch(Exception e) {
				log.error("获取操作员信息失败",e);
				Toast.makeText(mContext, "获取操作员信息失败", Toast.LENGTH_SHORT).show();
				mApplication.setOperator(null);
			}
		}
	};

	private void showVerson(){
		String bt = "nil";

		if(mService == null){
			bt = "正在连接...";
		}else{
			if(Constant.BANKPAYTYPE_YINGSHEN.equals(bankPayType)){
				bt = "ys";
			}else if(Constant.BANKPAYTYPE_NONGSHAN.equals(bankPayType)){
				bt = "ns";
			}
		}

		((TextView)findViewById(R.id.tv_version)).setText(StringUtil.getVersion(this) + " " + bt);
	}

	public  String getPayCloud(){
		String alipay = "";
		if("1".equals(payType)){	//支付宝
			alipay = "01,05,08,23,29";
		}else if("2".equals(payType)){ //微信
			alipay = "02,06,09,24,30";
		}else if("3".equals(payType)){
			alipay = "03,07,";
		}else if("4".equals(payType)){
			alipay = "17,";
		}else if("5".equals(payType)){
			alipay = "16,";
		}else if("6".equals(payType)){
			alipay = "19,";
		}else if("success".equals(payType)){
			alipay = "18,";
		}else if("8".equals(payType)){
			alipay = "20,";
		}
		return alipay;
	}



	public Intent initIntent(){
		if(totalMoney!=null){
			KeyboardStringUtil.getDiaplayString(totalMoney);
			mSummary = KeyboardStringUtil.changeY2F(totalMoney);
			mAmount = totalMoney;
		}else{
			mSummary = KeyboardStringUtil.getSummary();
			mAmount = KeyboardStringUtil.getAmount();
		}
		Intent intent = new Intent();
		intent.putExtra("amount", Long.parseLong(mSummary));// 金额统一以分为单位,long类型 Long.parseLong(StringUtil.changeY2F(amount)));
		return intent;
	}

	public int getSummary(){
		if(StringUtil.isEmpty(mSummary)){
			mSummary = "0";
		}
		return Integer.parseInt(mSummary.trim());
	}

	public void insertDB(String amount){
		RecordModel recordModel = new RecordModel();
		recordModel.setAmount(amount);
		recordModel.setOrderid(orderId);
		recordModel.setOperator_type(Constant.PAY_TYPE_BANKCARD);
		recordModel.setState("0");
		RecordDB rdb = new RecordDB();
		rdb.insertRecordModel(recordModel);
	}

	public void orderPrint(){
		try {
			if("1".equals(isFromType)){
				StringBuffer printdata = new StringBuffer();
				printdata.append("*line\n");// 打印虚线
				printdata.append("!qrcode 150 2\n ");
				printdata.append("*qrcode c "+orderNum+" 2\n");
				printdata.append("*text c "+orderNum+" \n");
				printdata.append("*text c 您好!凭二维码打印销售单。 \n");
				printdata.append(getString(R.string.print_cut_line));
				printdata.append("*feedline 2\n");
				byte[] printData = printdata.toString().getBytes(getString(R.string.print_encoding));
				printer.printByScript(PrintContext.defaultContext(), printData, 60, TimeUnit.SECONDS);
			}
		}catch(Exception e){
			e.printStackTrace();
			Toast.makeText(mContext, "订单号打印异常", Toast.LENGTH_SHORT).show();
		}
	}

	public void invoice(){
		if("1".equals(mApplication.getOperator().getIsInvoice())){
			try {
				AlertDialog dialog = new AlertDialog.Builder(PayActivity.this).setTitle("是否开票？")
						.setPositiveButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								returnBack("true");
							}
						})
						.setNegativeButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent();
								intent.setAction("com.fjums.thunderreceipt.BtSelectionActivity");
								intent.putExtra("APP_FLAG", "FJUMS");
								startActivity(intent);
							}
						}).create();
				dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
				dialog.show();
			}catch (Exception ex){

			}
		}else{
			returnBack("true");
		}
	}

	// 重打上一笔
	public void rePrint(String errInfo){
		AlertDialog dialog = new AlertDialog.Builder(PayActivity.this).setTitle("打印机异常:"+errInfo)
				.setPositiveButton("取消",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						orderPrint();
					}
				})
				.setNegativeButton("重新打印",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						printSomething();
					}
				}).create();
		dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
		dialog.show();
	}

	public void printSomething() {
		byte[] printData = null;
		try {
			PrinterStringUtil printUtil = new PrinterStringUtil(mContext, mApplication.getOperator());
			printData = printUtil.getPrintString(businessRstStr,PrinterStringUtil.MERCHANT_COPY,mPayType,mOpType);
			if(printData != null){
				PrinterResult scriptResult = printer.printByScript(PrintContext.defaultContext(), printData, 60, TimeUnit.SECONDS);
				if(scriptResult == PrinterResult.SUCCESS) {
					AlertDialog dialog = new AlertDialog.Builder(PayActivity.this).setTitle("是否打印第二联？")
							.setPositiveButton("取消",new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									//add 20170307 从人人公益过来的支付直接返回
									orderPrint();
									if (isFromWelfare) {
										isFromWelfare = false;
										onBackPressed();
									}else if(!StringUtil.isEmpty(isFromType)){
										returnBack("true");
									}else {
										// 闪电开票
										invoice();
									}
								}
							})
							.setNegativeButton("确定",new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									PrinterStringUtil printUtil = new PrinterStringUtil(mContext, mApplication.getOperator());
									try {
										byte[] printData = printUtil.getPrintString(businessRstStr,PrinterStringUtil.CUSTOMER_COPY,mPayType,mOpType);
										PrinterResult scriptResult = printer.printByScript(PrintContext.defaultContext(), printData, 60, TimeUnit.SECONDS);
										if(scriptResult != PrinterResult.SUCCESS) {
											rePrint(scriptResult.toString());
//									ToastUtil.showToast(mContext, "打印机异常:"+scriptResult, ToastUtil.WARNING);
										}else{
											//add 20170307 从人人公益过来的支付直接返回
											orderPrint();
											if (isFromWelfare) {
												isFromWelfare = false;
												onBackPressed();
											}else if(!StringUtil.isEmpty(isFromType)){
												returnBack("true");
											}else {
												// 闪电开票
												invoice();
											}
										}

									} catch (Exception e) {
										rePrint(e.toString());
//								ToastUtil.showToast(mContext, "打印机异常:"+e.toString(), ToastUtil.WARNING);
										e.printStackTrace();
									}
								}
							})
							.create();
					dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
					dialog.show();
				} else {
					rePrint(scriptResult.toString());
//					ToastUtil.showToast(mContext, "打印机异常:"+scriptResult, ToastUtil.WARNING);
				}
			}else{
				ToastUtil.showToast(mContext, "打印机数据异常", ToastUtil.WARNING);
			}
		} catch (Exception e) {
			rePrint(e.toString());
//			ToastUtil.showToast(mContext, "打印机异常:"+e.toString(), ToastUtil.WARNING);
			e.printStackTrace();
		}
	}

	// 打印机异常时，提示是否重新打印
	private void rePrint(){
		AlertDialog dialog = new AlertDialog.Builder(PayActivity.this).setTitle("是否开票？")
				.setPositiveButton("取消",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.setNegativeButton("确定",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent();
						intent.setAction("com.fjums.thunderreceipt.BtSelectionActivity");
						intent.putExtra("APP_FLAG","FJUMS");
						startActivity(intent);
					}
				}).create();
		dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
		dialog.show();
	}

	public void returnBack(String opType) {
		if("1".equals(isFromType)){
			String fromPackage = this.getIntent().getStringExtra("fromPackage");
			String fromActivity = this.getIntent().getStringExtra("fromActivity");
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			ComponentName cn = new ComponentName(fromPackage,fromActivity);
			intent.setComponent(cn);
			intent.putExtra("result", opType);
			intent.putExtra("mPayType",mPayType);
			intent.putExtra("backfrom", "market");
			startActivity(intent);
		}else if("2".equals(isFromType)){
			String fromPackage = this.getIntent().getStringExtra("fromPackage");
			String fromActivity = this.getIntent().getStringExtra("fromActivity");
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			ComponentName cn = new ComponentName(fromPackage,fromActivity);
			intent.setComponent(cn);
			intent.putExtra("result", opType);
			intent.putExtra("mPayType",mPayType);
			intent.putExtra("backfrom", "cloudpay");
			startActivity(intent);
		}

		if("false".equals(opType)){
			ToastUtil.showToast(mContext, "支付失败", ToastUtil.FAIL);
		}else{
			ToastUtil.showToast(mContext, "支付成功", ToastUtil.SUCCESS);
		}
		finish();
	}

	protected void onStart(){
		super.onStart();
	}
	@Override
	protected void onResume() {
		super.onResume();
		if(CloudPayApplication.from==1){

		}
		// 银盛支付（测试）
//		YSSDKManager.login(getApplicationContext(),"8fbc3fc243c182093e78172fe2c714fa");

		// 银盛支付（正式）
		try{
			YSSDKManager.login(getApplicationContext(),"39fe6fff0f59118f23e8ccbdf327c364");
		}catch(Exception e){
			e.printStackTrace();
			ToastUtil.showToast(mContext, "银盛支付授权异常"+e.toString(), ToastUtil.WARNING);
		}
		try {
			printer = mApplication.getPrinter();
			printer.init();
		}catch (Exception e){
			ToastUtil.showToast(mContext, "打印初始化异常"+e.toString(), ToastUtil.WARNING);
			e.printStackTrace();
		}
	}

	public void pay_success(){
		if("2".equals(mApplication.isMT())){
			returnBack("true");
		}else if(Constant.PAY_TYPE_ALIPAY.equals(mPayType)
				|| Constant.PAY_TYPE_MICROPAY.equals(mPayType)){
			// 打印
			if(Constant.IS_PRINT_AFTERPAY){
				printSomething();
			}else{
				returnBack("true");
			}
		}else if(Constant.PAY_TYPE_ALIPAY_NS.equals(mPayType)
				|| Constant.PAY_TYPE_MICROPAY_NS.equals(mPayType)
				|| Constant.PAY_TYPE_ALIPAY_YS.equals(mPayType)
				|| Constant.PAY_TYPE_MICROPAY_YS.equals(mPayType)
				|| Constant.PAY_TYPE_BANKCARD.equals(mPayType)
				|| Constant.PAY_TYPE_BANKCARD_NS.equals(mPayType)
				|| Constant.PAY_TYPE_CASH.equals(mPayType)
				){
			orderPrint();
			returnBack("true");
		}else if(Constant.PAY_TYPE_ALIPAY_LH.equals(mPayType)
				|| Constant.PAY_TYPE_MICROPAY_LH.equals(mPayType)
				|| Constant.PAY_TYPE_HB_LH.equals(mPayType)
				||Constant.PAY_TYPE_ALIPAY_WF.equals(mPayType)
				|| Constant.PAY_TYPE_MICROPAY_WF.equals(mPayType)){
			printSomething();
		}
	}

	public void pay_error(){
		new AlertDialog.Builder(PayActivity.this).setTitle("支付异常")
				.setMessage(businessRstStr)
				.setPositiveButton("取消",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						returnBack("false");
					}
				})
				.setPositiveButton("确定",new DialogInterface.OnClickListener() {//添加确定按钮
					@Override
					public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
						returnBack("false");
					}
				}).show();
	}

	public void pay_fail(){
		returnBack("false");
	}

	public void pay_wait(){
		new AlertDialog.Builder(PayActivity.this).setTitle("确认提示")
				.setMessage(businessRstStr)
				.setPositiveButton("取消",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						returnBack("false");
					}
				})
				.setPositiveButton("确定",new DialogInterface.OnClickListener() {//添加确定按钮
					@Override
					public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件,重新发起支付
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(scanCode, "1");
					}
				}).show();
	}
	@Override
	protected void onPause() {
		super.onPause();
		// 银盛支付
		YSSDKManager.logout(PayActivity.this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
//		unbindService(mServiceConnection);
	}


	@SuppressLint("HandlerLeak")
	private Handler mPayHandler = new Handler() {
		public void handleMessage(Message msg) {
			businessRstStr = (String) msg.obj; // 扫描到的授权码或支付后返回的消息
			switch (msg.what) {
				case Constant.BUSINESS_SUCCESS :
					pay_success();
					break;
				case Constant.BUSINESS_FAILED : // 支付失败
					pay_fail();
					break;
				case Constant.BUSINESS_ERROR : // 支付失败
					pay_error();
					break;
				case Constant.BUSINESS_WAIT : // 支付失败
					pay_wait();
					break;
				default:
					break;
			}
		}
	};

	// 支付宝或微信支付异步任务
	public class PayAsyncTask extends AsyncTask<String, Void, String> {

		private ObjectGenerator generator = new ObjectGenerator(mContext);

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			String jsonStr = "";
			String rs = "";
			try {
				switch(mOpType){
					case Constant.KEYBOARD_OP_TYPE_PAY: // 支付
						jsonStr = generator.getScanPayReqStr(mPayType,getSummary(), mApplication.getOperator(), params);
						break;
					case Constant.KEYBOARD_OP_TYPE_RETURN: // 退款
						jsonStr = generator.getScanRetundReqStr(mPayType,getSummary(), mApplication.getOperator(),params);
						break;
				}
				if(Constant.PAY_TYPE_BANKCARD.equals(mPayType)){
					log.info(jsonStr);
				}
				rs = WebserviceRequset.requsetService(jsonStr,mApplication.getServiceAddress());
			} catch (Exception e) {
				e.printStackTrace();
				log.error("网络请求异常："+jsonStr,e);
			}
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgress.dismiss();
			//如果支付成功，关闭扫描页面
			JSONObject resultJSON = null;
			Message message = new Message();
			try {
				if("anyType{}".equals(result)){
					message.obj = "返回值anyType{}:获取不到服务器证书文件";
					message.what = Constant.BUSINESS_ERROR;
				}else{
					resultJSON = new JSONObject(result);
					String resultCode = resultJSON.getString("result");
					String returnMsg = resultJSON.getString("return_msg");
					message.obj = returnMsg;
					if(resultCode.equals("SUCCESS")) {
						// 解析result判断订单支付情况，返回MainActivity或者弹框提示
						message.what = Constant.BUSINESS_SUCCESS;//处理打印，调回页面业务

						//20170225 添加支付成功广播
						int money = Integer.parseInt(mSummary);

						Log.e(">>>>result>", result);
						String serialNum = "";
						try{
							JSONObject jsonMsg = new JSONObject(returnMsg);
							serialNum =  jsonMsg.getString("outTradeNo");//流水号
						}catch(Exception e){
							e.printStackTrace();
						}
						if (money > 0) {
							Intent intent=new Intent();
							intent.setAction("cn.yy.pos.launcher.broadcastReceiver.AmountBroadcastReceiver.PAYMENT_SUCCESS");
							intent.putExtra("money", money);
							intent.putExtra("payId", serialNum);
							sendBroadcast(intent);
						}else Log.e(">>>>>>mSummary", "mSummary is null");

					}else if(resultCode.equals("FAIL")) {
						message.what = Constant.BUSINESS_FAILED;
					}else if(resultCode.equals("WAIT")) {
						message.what = Constant.BUSINESS_WAIT;
					}else {
						message.what = Constant.BUSINESS_ERROR;
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
				log.error("网络请求异常："+result,e);
				message.obj = "数据解析错误";
				message.what = Constant.BUSINESS_ERROR;
			} finally {
				mPayHandler.sendMessage(message);
			}
		}
	};
}
